package com.mmall.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mmall.common.Const;
import com.mmall.common.ResponseCode;
import com.mmall.common.ServerResponse;
import com.mmall.common.TokenCache;
import com.mmall.dao.UserMapper;
import com.mmall.pojo.User;
import com.mmall.service.IUserService;
import com.mmall.utils.MD5Util;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.security.provider.MD5;

import javax.servlet.http.HttpSession;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

@Service(value = "iUserService")
public class UserServiceImpl implements IUserService {


    @Autowired
    private UserMapper userMapper;

    public ServerResponse<User> login(String username, String password) {
        int count = userMapper.checkUserName(username);
        if (count == 0) {
            return ServerResponse.createByErrorMessage("用户不存在");
        }

        String passwordHex = MD5Util.MD5EncodeUtf8(password + Const.salt);
        User user = userMapper.selectLogin(username, passwordHex);
        if (user == null) {
            return ServerResponse.createByErrorMessage("登录失败，用户名或密码错误");
        }

        //不显示密码
        user.setPassword(StringUtils.EMPTY);

        return ServerResponse.createBySuccess(user);

    }


    public ServerResponse register(User user) {
        int count = userMapper.checkUserName(user.getUsername());
        if (count > 0) {
            return ServerResponse.createByErrorMessage("用户以存在");
        }

        count = userMapper.checkEmail(user.getEmail());
        if (count > 0) {
            return ServerResponse.createByErrorMessage("邮箱以存在");
        }

        //设置用户角色
        user.setRole(Const.Role.ROLE_CUSTOMER.getCode());

        //加密密码
        String md5Passwd = MD5Util.MD5EncodeUtf8(user.getPassword());
        user.setPassword(md5Passwd);

        count = userMapper.insertSelective(user);
        if (count > 0) {
            return ServerResponse.createBySuccessMessage("用户创建成功");
        }
        return ServerResponse.createByErrorMessage("用户创建失败");
    }


    public ServerResponse checkValid(String inform, String type) {
        if (StringUtils.isNotBlank(type)) {
            if (Const.CheckType.USER_NAME.equals(type)) {
                int count = userMapper.checkUserName(inform);
                if (count > 0) {
                    return ServerResponse.createByErrorMessage("用户以存在");
                }
            } else if (Const.CheckType.USER_EMAIL.equals(type)) {
                int count = userMapper.checkEmail(inform);
                if (count > 0) {
                    return ServerResponse.createByErrorMessage("邮箱以存在");
                }
            }
        } else {
            return ServerResponse.createByErrorMessage("校验失败");
        }
        return ServerResponse.createBySuccessMessage("校验成功");
    }


    public ServerResponse getUserQuestion(String username) {
        String question = userMapper.selectQuestionByUsername(username);
        if (StringUtils.isBlank(question)) {
            return ServerResponse.createByErrorMessage("用户不存在或未设置找回密码问题");
        }
        return ServerResponse.createBySuccess(question);
    }

    public ServerResponse checkAnswer(String username, String question, String answer) {
        int count = userMapper.checkAnswer(username, question, answer);
        if (count > 0) {
            //数据匹配，问题和答案都是该用户的
            //生成token并传给用户
            String forgetToken = UUID.randomUUID().toString();
            TokenCache.setCache(username, forgetToken);
            return ServerResponse.createBySuccess(forgetToken);
        }
        return ServerResponse.createByErrorMessage("校验失败");
    }

    public ServerResponse forgetResetPassword(String username, String newPassword, String forgetToken) {
        if (StringUtils.isBlank(forgetToken)) {
            return ServerResponse.createByErrorMessage("参数错误，token需要传递");
        }
        String cache = TokenCache.getCache(username);
        if (StringUtils.isBlank(cache)) {
            return ServerResponse.createByErrorMessage("token不存在或已过期");
        }

        if (!StringUtils.equals(cache, forgetToken)) {
            return ServerResponse.createByErrorMessage("token错误");
        }

        String md5PassWord = MD5Util.MD5EncodeUtf8(newPassword + Const.salt);
        User user = new User();
        user.setPassword(md5PassWord);
        int count = userMapper.updateByUsername(username, md5PassWord);
        if (count > 0) {
            return ServerResponse.createBySuccessMessage("更新密码成功");
        }
        return ServerResponse.createByErrorMessage("更新密码失败");
    }

    public ServerResponse restPassword(User user, String newPassword, String oldPassword) {
        //验证用户以及旧密码
        int count = userMapper.checkOldPasswordByUserId(user.getId(), MD5Util.MD5EncodeUtf8(oldPassword + Const.salt));
        if (count > 0) {
            String md5Password = MD5Util.MD5EncodeUtf8(newPassword);
            user.setPassword(md5Password);

            count = userMapper.updateByPrimaryKeySelective(user);
            if (count > 0) {
                return ServerResponse.createBySuccessMessage("更新密码成功");
            }
            return ServerResponse.createByErrorMessage("更新密码失败");
        }
        return ServerResponse.createByErrorMessage("更新失败，用户信息不匹配");
    }


    public ServerResponse updateUserInformation(User user) {
        //校验更改的用户名和邮箱是否已经存在
        ServerResponse response = checkValid(user.getUsername(), Const.CheckType.USER_NAME);
        if (!response.is_success()) {
            return response;
        }
        response = checkValid(user.getEmail(), Const.CheckType.USER_EMAIL);
        if (!response.is_success()) {
            return response;
        }

        User userUpdate = new User();
        userUpdate.setId(user.getId());
        userUpdate.setEmail(user.getEmail());
        userUpdate.setPhone(user.getPhone());
        userUpdate.setQuestion(user.getQuestion());
        userUpdate.setAnswer(user.getAnswer());

        int count = userMapper.updateByPrimaryKeySelective(userUpdate);
        if (count > 0) {
            return ServerResponse.createBySuccess("用户信息更新成功", userUpdate);
        }

        return ServerResponse.createBySuccessMessage("更新用户信息失败");
    }


    public ServerResponse checkAdminRole(HttpSession session) {
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByError(ResponseCode.NEED_LOGIN.getCode(), ResponseCode.NEED_LOGIN.getMsg());
        }
        User user_info = userMapper.selectByPrimaryKey(user.getId());
        Integer role = user_info.getRole();
        if (Const.Role.ROLE_ADMIN.getCode() == role) {
            return ServerResponse.createBySuccess();
        }
        return ServerResponse.createByErrorMessage("非管理员，无权限操作");
    }

    //后台相关接口实现
    public ServerResponse<User> manageLogin(String username, String password) {
        ServerResponse<User> loginResponse = this.login(username, password);
        if (!loginResponse.is_success()) {
            return loginResponse;
        }
        User user = loginResponse.getData();
        if (Const.Role.ROLE_ADMIN.getCode() == user.getRole()) {
            user.setPassword(StringUtils.EMPTY);
            return ServerResponse.createBySuccess("管理员登录成功", user);
        }
        return ServerResponse.createByErrorMessage("管理员登录失败");

    }


    public ServerResponse<List<User>> list(Integer pageNum, Integer pageSize) {

        PageHelper.startPage(pageNum, pageSize);

        List<User> users = userMapper.selectAll();
        Iterator<User> iterator = users.iterator();
        while (iterator.hasNext()) {
            iterator.next().setPassword(StringUtils.EMPTY);
        }
        PageInfo pageInfo = new PageInfo(users);
        return ServerResponse.createBySuccess(users);

    }

}
